<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#409EFF"><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.total_count || 0 }}</div>
              <div class="stat-label">总开奖期数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#67C23A"><Cpu /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.total_predictions || 0 }}</div>
              <div class="stat-label">AI预测次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#E6A23C"><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.win_rate || 0 }}%</div>
              <div class="stat-label">中奖率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#F56C6C"><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">¥{{ statistics.total_win_amount || 0 }}</div>
              <div class="stat-label">总中奖金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>快速操作</span>
            </div>
          </template>
          
          <div class="quick-actions">
            <el-button
              type="primary"
              size="large"
              icon="Refresh"
              @click="updateLotteryData"
              :loading="updating"
            >
              更新双色球数据
            </el-button>
            
            <el-button
              type="success"
              size="large"
              icon="DataAnalysis"
              @click="goToAnalysis"
            >
              AI数据分析
            </el-button>
            
            <el-button
              type="warning"
              size="large"
              icon="PieChart"
              @click="goToReports"
            >
              查看报表
            </el-button>
            
            <el-button
              type="info"
              size="large"
              icon="Connection"
              @click="showMutualExclusionDialog"
            >
              双色球互斥分析
            </el-button>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新开奖</span>
            </div>
          </template>
          
          <div v-if="latestDraw" class="latest-draw">
            <div class="draw-info">
              <div class="draw-number">第{{ latestDraw.draw_number }}期</div>
              <div class="draw-date">{{ latestDraw.draw_date }}</div>
            </div>
            
            <div class="ball-numbers">
              <div class="red-balls">
                <span
                  v-for="ball in redBalls"
                  :key="ball"
                  class="ball red-ball"
                >
                  {{ formatBallNumber(ball) }}
                </span>
              </div>
              <div class="blue-balls">
                <span class="ball blue-ball">
                  {{ formatBallNumber(latestDraw.blue_ball) }}
                </span>
              </div>
            </div>
          </div>
          
          <div v-else class="no-data">
            暂无开奖数据
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最近预测记录</span>
            </div>
          </template>
          
          <el-table :data="recentPredictions" style="width: 100%">
            <el-table-column prop="start_draw" label="开始期数" width="120" />
            <el-table-column prop="end_draw" label="结束期数" width="120" />
            <el-table-column prop="data_count" label="数据条数" width="100" />
            <el-table-column prop="win_amount" label="中奖金额" width="120">
              <template #default="scope">
                <span :class="{ 'win-amount': scope.row.win_amount > 0 }">
                  ¥{{ formatAmount(scope.row.win_amount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="预测时间" width="180" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                  v-if="!scope.row.actual_result"
                  type="primary"
                  size="small"
                  @click="verifyPrediction(scope.row.id)"
                >
                  验证结果
                </el-button>
                <span v-else class="verified">已验证</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 互斥分析对话框 -->
    <el-dialog
      v-model="mutualExclusionDialogVisible"
      title="双色球互斥分析"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="mutual-exclusion-form">
        <el-form :model="mutualExclusionForm" label-width="120px">
          <el-form-item label="起始期数">
            <el-select
              v-model="mutualExclusionForm.start_draw"
              placeholder="选择起始期数（可选）"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="draw in drawOptions"
                :key="draw"
                :label="draw"
                :value="draw"
              />
            </el-select>
            <div class="form-hint">
              <el-text type="info" size="small">不选择则从最新期数开始分析</el-text>
            </div>
          </el-form-item>
          
          <el-form-item label="分析期数">
            <el-input-number
              v-model="mutualExclusionForm.period_count"
              :min="10"
              :max="500"
              :step="10"
              placeholder="选择分析期数"
            />
            <div class="form-hint">
              <el-text type="info" size="small">建议选择50-200期进行分析，期数越多分析越准确</el-text>
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="dialog-actions">
        <el-button @click="mutualExclusionDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="startMutualExclusionAnalysis"
          :loading="mutualExclusionAnalyzing"
        >
          {{ mutualExclusionAnalyzing ? '分析中...' : '开始分析' }}
        </el-button>
      </div>
      
      <!-- 分析结果 -->
      <div v-if="mutualExclusionResult" class="analysis-result">
        <el-divider content-position="left">分析结果</el-divider>
        
        <div class="result-summary">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="summary-card">
                <template #header>
                  <div class="card-header">
                    <span>分析期数</span>
                  </div>
                </template>
                <div class="summary-value">{{ mutualExclusionResult.period_count }}</div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="summary-card">
                <template #header>
                  <div class="card-header">
                    <span>强互斥关系</span>
                  </div>
                </template>
                <div class="summary-value">{{ mutualExclusionResult.analysis.strong_exclusions.length }}</div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="summary-card">
                <template #header>
                  <div class="card-header">
                    <span>弱互斥关系</span>
                  </div>
                </template>
                <div class="summary-value">{{ mutualExclusionResult.analysis.weak_exclusions.length }}</div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
                 <!-- 强互斥关系表格 -->
         <div v-if="mutualExclusionResult.analysis.strong_exclusions.length > 0" class="exclusion-section">
           <h4>📊 强互斥关系（从未一起出现）</h4>
                                  <el-table 
              :data="mutualExclusionResult.analysis.strong_exclusions" 
              stripe
              :pagination="{
                pageSize: 50,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }"
            >
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="ball1" label="红球1" width="80">
               <template #default="scope">
                 <span class="ball-number">{{ formatBallNumber(scope.row.ball1) }}</span>
               </template>
             </el-table-column>
             <el-table-column prop="ball2" label="红球2" width="80">
               <template #default="scope">
                 <span class="ball-number">{{ formatBallNumber(scope.row.ball2) }}</span>
               </template>
             </el-table-column>
             <el-table-column prop="ball1_count" label="红球1出现次数" width="120" />
             <el-table-column prop="ball2_count" label="红球2出现次数" width="120" />
             <el-table-column prop="expected_co" label="期望共现" width="100" />
             <el-table-column prop="co_occurrence" label="实际共现" width="100" />
           </el-table>
        </div>
        
                 <!-- 弱互斥关系表格 -->
         <div v-if="mutualExclusionResult.analysis.weak_exclusions.length > 0" class="exclusion-section">
           <h4>📈 弱互斥关系（很少一起出现）</h4>
                                  <el-table 
              :data="mutualExclusionResult.analysis.weak_exclusions" 
              stripe
              :pagination="{
                pageSize: 50,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }"
            >
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="ball1" label="红球1" width="80">
               <template #default="scope">
                 <span class="ball-number">{{ formatBallNumber(scope.row.ball1) }}</span>
               </template>
             </el-table-column>
             <el-table-column prop="ball2" label="红球2" width="80">
               <template #default="scope">
                 <span class="ball-number">{{ formatBallNumber(scope.row.ball2) }}</span>
               </template>
             </el-table-column>
             <el-table-column prop="ball1_count" label="红球1出现次数" width="120" />
             <el-table-column prop="ball2_count" label="红球2出现次数" width="120" />
             <el-table-column prop="expected_co" label="期望共现" width="100" />
             <el-table-column prop="co_occurrence" label="实际共现" width="100" />
             <el-table-column prop="exclusion_strength" label="互斥强度" width="100">
               <template #default="scope">
                 <el-progress
                   :percentage="scope.row.exclusion_strength * 100"
                   :format="(val) => scope.row.exclusion_strength.toFixed(3)"
                   :stroke-width="8"
                 />
               </template>
             </el-table-column>
           </el-table>
        </div>
        
        <!-- 详细分析报告 -->
        <div class="analysis-report">
          <h4>📋 详细分析报告</h4>
          <div class="report-content">
            <pre>{{ mutualExclusionResult.analysis.analysis_report }}</pre>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Document,
  Cpu,
  Trophy,
  Money,
  Refresh,
  DataAnalysis,
  PieChart,
  Connection
} from '@element-plus/icons-vue'
import api from '@/api'

export default {
  name: 'Dashboard',
  components: {
    Document,
    Cpu,
    Trophy,
    Money,
    Refresh,
    DataAnalysis,
    PieChart,
    Connection
  },
  setup() {
    const router = useRouter()
    const statistics = ref({})
    const updating = ref(false)
    const chartData = ref([])
    
    const latestDraw = ref(null)
    const recentPredictions = ref([])
    
    const redBalls = ref([])
    
    // 互斥分析相关
    const mutualExclusionDialogVisible = ref(false)
    const mutualExclusionAnalyzing = ref(false)
    const mutualExclusionResult = ref(null)
    const drawOptions = ref([])
    const mutualExclusionForm = reactive({
      start_draw: '',
      period_count: 50
    })
    
    const loadData = async () => {
      try {
        // 加载统计数据
        const statsResponse = await api.reports.getSummary()
        statistics.value = statsResponse.data
        
        // 加载最新开奖
        const statsResponse2 = await api.lottery.getList({ page: 1, per_page: 1 })
        if (statsResponse2.data.data.length > 0) {
          latestDraw.value = statsResponse2.data.data[0]
          redBalls.value = [
            latestDraw.value.red_ball_1,
            latestDraw.value.red_ball_2,
            latestDraw.value.red_ball_3,
            latestDraw.value.red_ball_4,
            latestDraw.value.red_ball_5,
            latestDraw.value.red_ball_6
          ]
        }
        
        // 加载最近预测
        const predictionsResponse = await api.ai.getPredictions({ page: 1, per_page: 5 })
        recentPredictions.value = predictionsResponse.data.data
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      }
    }
    
    const updateLotteryData = async () => {
      try {
        updating.value = true
        await api.lottery.update()
        ElMessage.success('数据更新成功')
        await loadData()
      } catch (error) {
        console.error('更新数据失败:', error)
        ElMessage.error('更新数据失败')
      } finally {
        updating.value = false
      }
    }
    
    const showMutualExclusionDialog = async () => {
      mutualExclusionDialogVisible.value = true
      mutualExclusionResult.value = null
      
      // 加载期数选项
      try {
        const response = await api.lottery.getList({ page: 1, per_page: 1000 })
        const data = response.data.data || []
        
        // 按日期倒序排列（最新的在前面）
        const sortedData = data.sort((a, b) => {
          const dateA = new Date(a.draw_date)
          const dateB = new Date(b.draw_date)
          return dateB - dateA
        })
        
        drawOptions.value = sortedData.map(item => item?.draw_number || '').filter(Boolean)
      } catch (error) {
        console.error('加载期数选项失败:', error)
        ElMessage.error('加载期数选项失败')
      }
    }
    
    const startMutualExclusionAnalysis = async () => {
      try {
        mutualExclusionAnalyzing.value = true
        ElMessage.info('正在分析互斥关系，请稍候...')
        
        const requestData = {
          period_count: mutualExclusionForm.period_count
        }
        
        // 如果选择了起始期数，则添加到请求数据中
        if (mutualExclusionForm.start_draw) {
          requestData.start_draw = mutualExclusionForm.start_draw
        }
        
        const response = await api.ai.mutualExclusion(requestData)
        
        mutualExclusionResult.value = response.data
        ElMessage.success('互斥分析完成！')
        
      } catch (error) {
        console.error('互斥分析失败:', error)
        ElMessage.error('互斥分析失败: ' + (error.response?.data?.error || error.message || '未知错误'))
      } finally {
        mutualExclusionAnalyzing.value = false
      }
    }
    
    const goToAnalysis = () => {
      router.push('/ai-analysis')
    }
    
    const goToReports = () => {
      router.push('/reports')
    }
    
    const verifyPrediction = async (id) => {
      try {
        await api.ai.verify({ prediction_id: id })
        ElMessage.success('验证完成')
        await loadData()
      } catch (error) {
        console.error('验证失败:', error)
        ElMessage.error('验证失败')
      }
    }
    
    const formatAmount = (amount) => {
      if (amount === null || amount === undefined || amount === '') {
        return '0'
      }
      return amount.toString()
    }

    const formatBallNumber = (number) => {
      if (number === null || number === undefined) {
        return '00';
      }
      return number.toString().padStart(2, '0');
    };
    
    onMounted(() => {
      loadData()
    })
    
          return {
        updating,
        statistics,
        latestDraw,
        recentPredictions,
        redBalls,
        updateLotteryData,
        showMutualExclusionDialog,
        startMutualExclusionAnalysis,
        mutualExclusionDialogVisible,
        mutualExclusionAnalyzing,
        mutualExclusionResult,
        mutualExclusionForm,
        drawOptions,
        goToAnalysis,
        goToReports,
        verifyPrediction,
        formatAmount,
        formatBallNumber
      }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  margin-right: 20px;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.quick-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.card-header {
  font-weight: bold;
  color: #333;
}

/* 互斥分析样式 */
.mutual-exclusion-form {
  margin-bottom: 20px;
}

.form-hint {
  margin-top: 8px;
}

.dialog-actions {
  text-align: right;
  margin-top: 20px;
}

.analysis-result {
  margin-top: 20px;
}

.result-summary {
  margin-bottom: 20px;
}

.summary-card {
  text-align: center;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.exclusion-section {
  margin-bottom: 30px;
}

.exclusion-section h4 {
  margin-bottom: 15px;
  color: #333;
  font-weight: 600;
}

.ball-number {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  font-weight: bold;
  font-size: 12px;
}

.analysis-report {
  margin-top: 30px;
}

.analysis-report h4 {
  margin-bottom: 15px;
  color: #333;
  font-weight: 600;
}

.report-content {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border-left: 4px solid #409eff;
}

.report-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'SF Pro Text', 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  font-size: 14px;
  line-height: 1.6;
  color: #2c3e50;
}

.latest-draw {
  text-align: center;
}

.draw-info {
  margin-bottom: 15px;
}

.draw-number {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.draw-date {
  font-size: 14px;
  color: #666;
}

.ball-numbers {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.red-balls {
  display: flex;
  gap: 5px;
}

.blue-balls {
  margin-left: 10px;
}

.ball {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  font-size: 12px;
  font-weight: bold;
  color: white;
}

.red-ball {
  background-color: #f56c6c;
}

.blue-ball {
  background-color: #409eff;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.win-amount {
  color: #67c23a;
  font-weight: bold;
}

.verified {
  color: #67c23a;
  font-size: 12px;
}
</style> 